<?php
/**
 * Note:     [Description]
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/2/7 16:13
 */
declare(strict_types=1);

namespace App\Service;

use App\Enums\DataScopeEnum;
use App\Model\RoleModel;
use App\Model\UserModel;

/**
 * Note:     数据权限服务
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/2/7 16:13
 * Class DataService
 *
 * @package App\Service
 */
class DataService
{
    /**
     * 获取数据权限
     *
     * @param UserModel $userModel
     *
     * @return array
     */
    public function getDeptIds(UserModel $userModel): array
    {
        // 用于存储部门id
        $deptIds = [];

        // 查询用户角色
        /** @var RoleService $roleService */
        $roleService = app(RoleService::class);
        $roleList    = $roleService->findByUserId($userModel->userId);

        // 获取对应的部门ID
        foreach ($roleList as $role) {
            $dataScopeEnum = DataScopeEnum::find($role['role_data_scope']);

            if (!$dataScopeEnum) {
                continue;
            }

            switch ($dataScopeEnum->getEnumId()) {
                case DataScopeEnum::THIS_LEVEL:
                    $dept      = $userModel->dept ?: [];
                    $deptId    = $dept['id'] ?? 0;
                    $deptIds[] = $deptId;
                    break;
                case DataScopeEnum::CUSTOMIZE:
                    $deptIds[] = $this->getCustomize($deptIds, $role);
                    break;
                default:
                    return [];
            }
        }

        return $deptIds;
    }

    /**
     * 获取自定义的数据权限
     *
     * @param array $deptIds 部门ID
     * @param array $role    角色
     *
     * @return array 数据权限ID
     */
    public function getCustomize(array $deptIds, array $role)
    {
        /** @var DeptService $deptService */
        $deptService = app(DeptService::class);
        $depts       = $deptService->findByRoleId($role['id']);
        foreach ($depts as $dept) {
            $deptIds[]    = $dept['id'];
            $deptChildren = $deptService->findByPId($dept['id']);
            if ($deptChildren) {
                $children = $deptService->getDeptChildren($deptChildren);
                array_push($deptIds, ...$children);
            }
        }

        return $deptIds;
    }
}
